<?php

namespace App\Http\Controllers\Api;

use App\Cinema;
use App\DateSession;
use App\Film;
use App\FilmTicket;
use App\LayoutFilm;
use App\Playthrough;
use App\PricePlan;
use App\Priceplantickettypes;
use App\Project;
use App\Screen;
use App\Seats;
use App\Session;
use App\SessionSeat;
use App\ShowtimeSchedule;
use App\TicketType;
use Barryvdh\Reflection\DocBlock;
use Carbon\Carbon;
use Hamcrest\Core\SampleBaseClass;
use Illuminate\Http\Request;

class SessionController extends BaseController
{
    public $user;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->user = $this->is_login($request);
    }

    //查看放映计划列表
    public function index(Request $request){

        if (!$this->user['data']->can(['buy_ticket','showtime_schedule_table','admin_bound_ticket'])){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        $user_type = $this->user['data']['type'];

        $cinema_name = $request->cinema_name;
        $start_time = $request->start_time;
        $end_time = $request->end_time;
        $film_code = $request->film_code;
        $film_name = $request->film_name;
        $screen_name = $request->screen_name ;
        $sales_flag = $request->sales_flag;
        $order_by = $request->order_by;
        $is_normal = $request->is_normal;

        if (!$end_time&&$start_time){
            $end_time = $start_time;
        }
        $order_by = $order_by?'desc':'asc';

        $showtime_list = \DB::table('showtime_schedules');
        $user_type==2&&$showtime_list->where('cinema_code','=',$cinema_code);
        $user_type==1&&$cinema_name&&$showtime_list->where('cinema_name','like','%'.$cinema_name.'%');
        $start_time&&$end_time&&$showtime_list->whereBetween('business_date',[$start_time,$end_time]);
        $sales_flag&&$showtime_list->where('end_time','>',date('Y-m-d H:i:s'));
        $screen_name&&$showtime_list->where('screen_name','like','%'.$screen_name.'%');
        $film_code&&$showtime_list->where('film_codes','like',','.$film_code);
        $film_name&&$showtime_list->where('film_names','like',',%'.$film_name.'%');
        $is_normal&&$showtime_list->where('status','=',1);
        $showtime_list->orderBy('start_time',$order_by);
        $data = $showtime_list->paginate(15);
        return success($data,'查询成功');
    }

    /**
     * @param Request $request
     * @return array
     * 查看排片计划列表
     */
    public function film_list(Request $request){

        if (!$this->user['data']->can(['layout_film','session_table','session_film','showtime_schedule_manager'])){
            return error('NoPermission');
        }

        $now = Carbon::now();
        $list = Project::select('projects.*','projects.id as project_id')->where('publish_end_date','>',$now)->get();
        return success($list,'查询成功');

    }

    /**
     * 保存排片计划
     */
    public function add_layout_film(Request $request){

        if (!$this->user['data']->can('layout_film')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];

        $cinema_status = Cinema::where('code','=',$cinema_code)->value('status');

        if ($cinema_status==0){
            return error('影院状态未申请不可排片');
        }

        //判断是否已过放映时间
        if (!$business_date=trim($request->input('business_date'))){
            return error('营业时间缺失');
        }
        if (!$screen_codes=trim($request->input('screen_codes'))){
            return error('影厅编码缺失');
        }

        $screen_codes = json_decode($screen_codes,true);
        $count = count($screen_codes);
        $res_count = Screen::whereIn('code',$screen_codes)
            ->where('status','!=',3)
            ->where('cinema_code','=',$cinema_code)
            ->count();
        if ($count!=$res_count){
            return error('影厅编码错误');
        }

        foreach ($screen_codes as $val){
            $count = Seats::where('screen_code','=',$val)->where('status','=',1)->count();
            if ($count==0){
                return error('影厅编码：'.$val.'没有座位信息');
            }
        }


        $showtime_count = Session::where(['cinema_code'=>$cinema_code,'business_date'=>$business_date])
            ->where('showtime_schedule_code','!=',null)->count();
        if ($showtime_count>0){
            return error('该放映日已开售');
        }
        $now_time = Carbon::now();
        $business_date = Carbon::parse($business_date);
        $date_start_time = Carbon::parse($business_date);
        $date_end_time = Carbon::parse($business_date);
        $date_start_time->hour=6;
        $date_end_time->hour =6;
        $date_end_time->day +=1;

    //    if ($now_time->gt($business_date)){
    //        return error('编排时间已超出发售时间');
    //    }

        if (!$data=trim($request->input('data'))){
            return error('排片详情为空');
        }

        $sessions = json_decode($data,true);
        $session_arr = [];
        foreach ($sessions as $key=>$val){
            $info = [];
            if (!isset($val['screen_code'])){
                return error('影厅编码不存在');
            }

           if (Carbon::now()->timestamp>$val['start_time']){
               return error('排场开时间不能在当前时间之前');
           }

            if (!in_array($val['screen_code'],$screen_codes)){
                return error('影厅编码不在保存影厅排片队列');
            }
            $info['screen_code'] = $val['screen_code'];



            if(!isset($val['price_plan_id'])){
                return error('票价方案id缺失');
            }
            $info['price_plan_id'] = $val['price_plan_id'];

            $price_plan=PricePlan::where('status','=',1)->find($val['price_plan_id']);
            $ticket_types = PriceplanTickettypes::where(['priceplan_tickettypes.price_plan_id'=>$val['price_plan_id']])
                ->join('ticket_types','priceplan_tickettypes.ticket_type_id','=','ticket_types.id')
                ->select('ticket_types.*')
                ->get();
            $price_plan['ticket_type'] = $ticket_types;
            if(!$price_plan){
                return error('票价方案不存在');
            }

            if (!isset($val['start_time'])){
                return error('排场开始时间不存在');
            }
            $info['start_time'] = $val['start_time'];


            if (!isset($val['end_time'])){
                return error('影厅编码不存在');
            }
            $info['end_time'] = $val['end_time'];

            if (!isset($val['share_proportion'])){
                return error('分账比不存在');
            }
            $info['share_proportion'] = $val['share_proportion'];


            if (!isset($val['duration'])){
                return error('影片时长不存在');
            }
            $info['duration'] = $val['duration'];


            if (!isset($val['language'])){
                return error('声音制式不存在');
            }
            $info['language'] = $val['language'];


            if (!isset($val['image'])){
                return error('画面类型不存在');
            }
            $info['image'] = $val['image'];


            if (!isset($val['frame'])){
                return error('影像制式不存在');
            }
            $info['frame'] = $val['frame'];

            if (!isset($val['project_id'])){
                return error('影片id不存在');
            }
            $info['project_id'] = $val['project_id'];

            $films = Film::where('image_types','like','%'.$val['image'].'%')
                ->where('frame_types','like','%'.$val['frame'].'%')
                ->where(['project_id'=>$val['project_id']])->first();
            
            $lowest_price = Film::where('image_types','like','%'.$val['image'].'%')
                ->where('frame_types','like','%'.$val['frame'].'%')
                ->where(['project_id'=>$val['project_id']])->value('lowest_price');
            if (!$films){
                return error('未找到对应的影片编码');
            }
            $info['film_code'] = $films->code;
            $info['film_id'] = $films->id;
            $info['film_name'] = $films->name;
            $info['screen_name'] = Screen::where('code','=',$info['screen_code'])->value('name');
            if (!isset($val['b24h_start_time'])){
                return error('排片开始时间datetime不存在');
            }
            $info['b24h_start_time'] = $val['b24h_start_time'];

            if (!isset($val['b24h_end_time'])){
                return error('排片结束时间datetime不存在');
            }
            $info['b24h_end_time'] = $val['b24h_end_time'];
//            if (!isset($val['created_at'])){
//                return error('创建时间create_at不存在');
//            }
//          
            $info['lowest_price'] = $lowest_price;
            $info['business_date'] = $business_date;
            $info['created_at'] = date('Y-m-d H:i:s');
            $info['cinema_code'] = $cinema_code;
            $info['status'] = 1;
            $info['code'] = get_session_code();
            $info['price_plan'] = json_encode($price_plan);
            $session_arr[] = $info;
        }
        //排片计划表先delete，后create
            $delete_res = Session::where(['business_date'=>$business_date,'cinema_code'=>$cinema_code])->delete();
            $delete_playthrough_status = Playthrough::where(['business_date'=>$business_date,'cinema_code'=>$cinema_code])->update(['status'=>2]);
            if (\DB::table('sessions')->insert($session_arr)){
                logs($this->user,json_encode(['type'=>'session','msg'=>'添加营业日'.$business_date.'预排片计划成功','info'=>$session_arr]));
                return success('','保存成功');
            }
            logs($this->user,json_encode(['type'=>'session','msg'=>'添加营业日'.$business_date.'预排片计划失败','info'=>$session_arr]));
            return error('保存失败');
    }

    /**
     * @param Request $request
     * 查看排片计划
     */
    public function get_layout_films(Request $request){

        if (!$this->user['data']->can(['layout_film','session_film','showtime_schedule_manager'])){
            return error('NoPermission');
        }


        if ($business_date = trim($request->input('business_date'))){
            error('营业日期缺失');
        }
        $cinema_code = $this->user['data']['cinema_code'];

        $screen_list = Screen::where(['cinema_code'=>$cinema_code])->where('status','!=',3)->get();
        $data = [];
        $has_showtime = $has_playthrough =0;
        $session_list = Session::where(['sessions.cinema_code'=>$cinema_code,'sessions.business_date'=>$business_date])
            // ->leftJoin('showtime_schedules','showtime_schedules.code','=','sessions.showtime_schedule_code')
            // ->select('sessions.*','showtime_schedules.status as showtime_schedule_status')
            // ->orderBy('sessions.start_time')
            ->join('films','sessions.film_code','=','films.code')
            ->join('screens','screens.code','=','sessions.screen_code')
            ->leftJoin('showtime_schedules','showtime_schedules.code','=','sessions.showtime_schedule_code')
            ->where(['films.status'=>1])
            ->select('sessions.*','films.id as film_id','films.name as film_name','screens.name as screen_name','showtime_schedules.status as showtime_schedule_status')
            ->orderBy('sessions.start_time')
            ->get();
        foreach ($screen_list as $val){
            $session_info =[];
            $session_info['sessions'] = [];
            $session_info['screen_code']=$val['code'];
            foreach ($session_list as $v){
                if ($v['showtime_schedule_status']!=2){
                    $v['showtime_schedule_status'] = $v['showtime_schedule_status']==''?0:$v['showtime_schedule_status'];

                    if ($val['code']==$v['screen_code']){
                        $session_info['sessions'][] = $v;
                    }

                    if ($v['showtime_schedule_code']!=''){
                        $has_showtime = 1;
                    }
                    if ($v['playthrough_flag']==1){
                        $has_playthrough = 1;
                    }
                }
            }
            $data[] = $session_info;
        }
        return success($data,'查询成功',array('has_showtime'=>$has_showtime,'has_playthrough'=>$has_playthrough));
    }

    /**
     * @param Request $request
     * @return array
     * 获取营业日前一天与后一天的排片信息
     */
    public function get_about_layout_films(Request $request){

        if (!$this->user['data']->can('layout_film')){
            return error('NoPermission');
        }

        if ($business_date = trim($request->input('business_date'))){
            error('营业日期缺失');
        }
        $business_date = Carbon::parse($business_date);
        $prev_business_date = Carbon::parse($business_date);
        $prev_business_date->day -= 1;
        $prev_business_date = $prev_business_date->toDateTimeString();
        $next_business_date = Carbon::parse($business_date);
        $next_business_date->day += 1;
        $next_business_date = $next_business_date->toDateTimeString();
        $business_date->hour +=6;
        $yestarday_last_second = $business_date->timestamp;
        $business_date->day +=1;
        $business_date->hour +=4;
        $tomorrow_last_second = $business_date->timestamp;

        $cinema_code = $this->user['data']['cinema_code'];

        $screen_list = Screen::where(['cinema_code'=>$cinema_code])->where('status','!=',3)->get();
        $data = [];
        $layout_prev_film_list = Session::where(['cinema_code'=>$cinema_code,'business_date'=>$prev_business_date])->where('end_time','>',$yestarday_last_second)
            ->join('films','sessions.film_code','=','films.code')
            ->where(['films.status'=>1])
            ->select('sessions.*','films.id as film_id','films.name as film_name')
            ->get();
        $layout_next_film_list = Session::where(['cinema_code'=>$cinema_code,'business_date'=>$next_business_date])->where('end_time','<',$tomorrow_last_second)
            ->join('films','sessions.film_code','=','films.code')
            ->where(['films.status'=>1])
            ->select('sessions.*','films.id as film_id','films.name as film_name')
            ->get();
        $layout_prev_films = [];
        $layout_next_films = [];
        foreach ($screen_list as $val){
            $layout_prev_film_info =[];
            $layout_prev_film_info['layout_prev_films']=[];
            $layout_next_film_info =[];
            $layout_next_film_info['layout_next_films']=[];
            $layout_prev_film_info['screen_code']=$val['code'];
            $layout_next_film_info['screen_code']=$val['code'];
            foreach ($layout_prev_film_list as $v){
                if ($val['code']==$v['screen_code']){
                    $layout_prev_film_info['layout_prev_films'][] = $v;
                }
            }
            foreach ($layout_next_film_list as $v){
                if ($val['code']==$v['screen_code']){
                    $layout_next_film_info['layout_next_films'][] = $v;
                }
            }
            $layout_prev_films[] = $layout_prev_film_info;
            $layout_next_films[] = $layout_next_film_info;
        }
        $data['prev_films'] = $layout_prev_films;
        $data['next_films'] = $layout_next_films;
        return success($data,'查询成功');
    }

    /**
     * @param Request $request
     * 编辑单条排片信息
     */
    public function edit_one_session_info(Request $request){
        $cinema_code = $this->user['data']['cinema_code'];

        if (!$id = $request->id){
            return error('场次id缺失');
        }

        if (!$price_plan_id = $request->price_plan_id){
            return error('票价方案id缺失');
        }

        if (!$share_proportion = $request->share_proportion){
            return error('分账比缺失');
        }

        if (!$seat_by_number = $request->seat_by_number){
            return error('是否对号入座缺失');
        }

        $session_info = Session::where(['cinema_code'=>$cinema_code])->find($id);
        if (!$session_info){
            return error('该排片信息不存在');
        }
        $price_plan = PricePlan::find($price_plan_id);


    }


    /**
     * @param Request $request
     * @return array
     * 添加连场
     */
    public function add_playthrough(Request $request){

        if (!$this->user['data']->can('session_film')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        //判断输入信息
        if (!$name = trim($request->input('name'))){
            return error('连场名称缺失');
        }
        if (!$screen_code = trim($request->input('screen_code'))){
            return error('影厅名称缺失');
        }
        if (!$business_date = trim($request->input('business_date'))){
            return error('营业日缺失');
        }
        $count = Session::where(['cinema_code'=>$cinema_code,'business_date'=>$business_date,'screen_code'=>$screen_code,'playthrough_name'=>$name])->count();
        if ($count>0){
            return error('该影厅在此营业日连场名称已存在，请重新确定名称');
        }
        if (!$layout_film_codes = trim($request->input('layout_film_codes'))){
            return error('排场code码集合缺失');
        }
        if (!$playthrough_price=trim($request->input('playthrough_price'))){
            return error('连场票价缺失');
        }
        if (!$seat_by_number=trim($request->input('seat_by_number'))){
            return error('对号入座信息缺失');
        }
        $layout_film_codes = explode(',',$layout_film_codes);

        $screen = Screen::where('status','!=',3)
            ->where(['code'=>$screen_code])->first();
        if (!$screen){
            return error('影厅不存在');
        }

        $count = count($layout_film_codes);
        if ($count<2){
            return error('设置连场最少2场排片或以上');
        }
        $res = Session::whereIn('code',$layout_film_codes)
            ->where(['cinema_code'=>$cinema_code,'playthrough_flag'=>2,'business_date'=>$business_date,'screen_code'=>$screen_code])
            ->select('project_id','id','code','playthrough_flag','seat_by_number','playthrough_name','playthrough_price','sequence')
            ->get();
        if ($count!=$res->count()){
            return error('存在已失效的排场编码');
        }
        $project_ids = [];

        $playthrough_price = json_decode($playthrough_price,true);
        $data = [];
        foreach ($res as $key=>$val){
            $info = [];
            $info['id'] = $val['id'];
            $info['playthrough_flag'] = 1;
            $info['seat_by_number'] = $seat_by_number;
            $info['playthrough_name'] = $name;
            $info['playthrough_price'] = $playthrough_price[$val['code']];
            $project_ids[] = $val['project_id'];
            $info['sequence'] = $key+1;
            $data[] = $info;
        }
        $project_ids = count(array_unique($project_ids));
        if ($count!=$project_ids){
            return error('相同的影片不可以做连场设置');
        }

        $res_playthrough = updateBatch('sessions',$data);
        if ($res_playthrough){
            logs($this->user,'设置营业日'.$business_date.'影厅：'.$screen->name.'连场计划'.$name.'成功');
            return success('','添加连场成功');
        }else{
            logs($this->user,'设置营业日'.$business_date.'影厅：'.$screen->name.'连场计划'.$name.'失败');
            return error('添加连场失败');
        }

    }

    /**
     * @param Request $request
     * 查询连场信息
     */
    public function get_playthrough(Request $request){

        if (!$this->user['data']->can('session_film')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$name = trim($request->input('name'))){
            return error('连场名称缺失');
        }
        if (!$screen_code = $request->input('screen_code')){
            return error('影厅编码缺失');
        }
        if (!$business_date = $request->input('business_date')){
            return error('营业日缺失');
        }

        $session_count = Session::where(['playthrough_name'=>$name,'playthrough_flag'=>1])->count();
        if ($session_count==0){
            return error('连场信息不存在');
        }
        $list = Session::where('sessions.playthrough_name','=',$name)
            ->join('films','sessions.film_code','=','films.code')
            ->where(['films.status'=>1,'sessions.status'=>1,'sessions.cinema_code'=>$cinema_code])
            ->select('sessions.*','films.name as film_name','films.lowest_price')->orderBy('sessions.start_time')
            ->get();
        return success($list,'查询成功');

    }

    /**
     * @param Request $request
     * @return array
     * 删除连场信息
     */
    public function delete_playthrough(Request $request){

        if (!$this->user['data']->can('session_film')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$name = trim($request->input('name'))){
            return error('连场名称缺失');
        }
        if (!$screen_code = $request->input('screen_code')){
            return error('影厅编码缺失');
        }
        if (!$business_date = $request->input('business_date')){
            return error('营业日缺失');
        }
        $session_lists = Session::where(['business_date'=>$business_date,'playthrough_name'=>$name,'playthrough_flag'=>1,'cinema_code'=>$cinema_code])->get();
        if ($session_lists->count()==0){
            return error('连场信息不存在');
        }
        if($session_lists[0]['showtime_schedule_code']){
            return error('已发售场次不可删除');
        }
        $data = [];
        foreach ($session_lists as $key=>$val){
            $info = [];
            $info['id'] = $val['id'];
            $info['playthrough_flag'] = 2;
            $info['playthrough_name'] = '';
            $info['playthrough_price'] = 0;
            $info['sequence'] = 0;
            $data[] = $info;
        }
        $res_playthrough = updateBatch('sessions',$data);
        if ($res_playthrough){
            logs($this->user,'删除营业日'.$business_date.'连场计划'.$name.'成功');
            return success('','删除连场成功');
        }else{
            logs($this->user,'删除营业日'.$business_date.'连场计划'.$name.'失败');
            return error('删除连场失败');
        }
    }

    /**
     * @param Request $request
     * @return array
     * 设置分账比
     */
    public function set_share_proportion(Request $request){

        if (!$this->user['data']->can('session_film')){
            return error('NoPermission');
        }

        if (!$id = $request->input('id')){
            return error('排片id缺失');
        }
        $layout_film_info = Session::where(['sessions.status'=>1])->find($id);
        if (!$layout_film_info){
            return error('排片信息不存在');
        }
        if($layout_film_info->showtime_schedule_code!=''){
            return error('已发售排片不可修改');
        }
        if ($layout_film_info->playthrough_flag==1){
            return error('排片为连场，不可修改');
        }

        if (!$share_proportion= $request->input('share_proportion')){
            return error('分账比未设置');
        }
        if (!is_numeric($share_proportion)){
            return error('分账比必须为数字类型');
        }
        if ($share_proportion<=0){
            return error('分账比必须大于0');
        }
        $layout_film_info->share_proportion = $share_proportion;
        if ($layout_film_info->save()){
            logs($this->user,'设置营业日'.$layout_film_info->business_date.'场次编码'.$layout_film_info->code.'分账比成功');
            return success($layout_film_info->id,'分账比设置成功');
        }else{
            logs($this->user,'设置营业日'.$layout_film_info->business_date.'场次编码'.$layout_film_info->code.'分账比失败');
            return error('分账比设置失败');
        }
    }


    /**
     * 添加放映计划
     */
    public function add(Request $request){

        if (!$this->user['data']->can('showtime_schedule_manager')){
            return error('NoPermission');
        }

        if (!$business_date = trim($request->input('business_date'))){
            return error('放映时间缺失');
        }

        $now_time = Carbon::parse(Carbon::now()->format('Y-m-d'));
        $business_date = Carbon::parse($business_date);

        if (!$business_date->gte($now_time)){
            return error('编排时间已超出发售时间');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        $session = ShowtimeSchedule::where(['status'=>1,'cinema_code'=>$cinema_code,'business_date'=>$business_date])->first();
        if ($session){
            return error('放映计划已存在');
        }
        $data = [];
        $session_arr = [];
        $cinema_info = Cinema::where(['code'=>$cinema_code])->where('status','!=',3)->first();

        //连场设置
        $session_playthrough_unique = \DB::table('sessions')->where(['cinema_code'=>$cinema_code,'business_date'=>$business_date,'playthrough_flag'=>1])
            ->groupBy(['playthrough_name','screen_code'])
            ->pluck('screen_code','playthrough_name');
        $session_playthrough_list = Session::where(['sessions.cinema_code'=>$cinema_code,'business_date'=>$business_date,'playthrough_flag'=>1])
            ->join('films','films.code','sessions.film_code')
            ->where('films.status','=',1)
            ->select('sessions.*','films.name as film_name')
            ->get();
        if ($session_playthrough_unique) {
            $infos = $this->group_sort($cinema_code,$business_date,$session_playthrough_unique,$session_playthrough_list->count(),$session_playthrough_list,$cinema_info);
            $data = $infos['info'];
            $session_arr = $infos['session_arr'];
        }

        //单场设置
        $session_list = Session::where(['sessions.cinema_code'=>$cinema_code,'business_date'=>$business_date,'playthrough_flag'=>2])
            ->join('films','films.code','sessions.film_code')
            ->where('films.status','=',1)
            ->select('sessions.*','films.name as film_name','films.lowest_price as lowest_price')
            ->get();

        if ($session_list->count()>0){
            foreach ($session_list as $val){
                $data_format = [];
                $sessions = [];
                $data_format['name'] = $val->film_name;
                $data_format['code'] = get_session_code();
                $sessions['id'] = $val['id'];
                $sessions['showtime_schedule_code'] = $data_format['code'];
                $session_arr[] = $sessions;

                $data_format['screen_code'] = $val->screen_code;
                $screen_name = Screen::where(['code'=>$val->screen_code,'cinema_code'=>$cinema_code])->where('status','!=',3)->value('name')?Screen::where(['code'=>$val->screen_code,'cinema_code'=>$cinema_code])->where('status','!=',3)->value('name'):'不存在';
                $data_format['screen_name'] = $screen_name;
                $data_format['cinema_code'] = $cinema_code;
                $data_format['cinema_name'] = $cinema_info['name'];
                $data_format['cinema_status'] = $cinema_info['status'];
                $data_format['business_date'] = $business_date;
                $data_format['playthrough_flag'] = 2;
                $data_format['lowest_price'] = $val['lowest_price'];
                $data_format['start_time'] = date('Y-m-d H:i:s',$val['start_time']);
                $data_format['end_time'] = date('Y-m-d H:i:s',$val['end_time']);
                $data_format['films'] = json_encode([$val]);
                $data_format['duration'] = $val['duration'];
                $price_plan = json_decode($val['price_plan'],true);
                $data_format['default_price'] = $price_plan['default_price'];
                $data_format['local_default_price'] = $price_plan['local_default_price'];
                $price_plan = json_decode($val['price_plan'],true);
                foreach ($price_plan['ticket_type'] as $v){
                    if ($v['ticket_price']<$val['lowest_price']){
                        return error('影片'.$val->film_name.'票价方案中最低价格小于影片最低票价');
                    }
                }
                $data_format['price_plan'] = $val['price_plan'];
                $data_format['seat_by_number'] = $val['seat_by_number'];
                $data_format['film_names'] = ','.$val['film_name'];
                $data_format['film_codes'] = ','.$val['film_code'];
                $data_format['project_ids'] = ','.$val['project_id'];
                $data_format['created_at'] = date('Y-m-d H:i:s');
                $data_format['updated_at'] = date('Y-m-d H:i:s');
                $data[] = $data_format;
            }
        }
        $film_tickets = $this->add_session_seat($data);

        if (count($film_tickets)==0){
            return error('电影票池生成失败');
        }

        \DB::beginTransaction();
        try{

            $showtime_schedules = ShowtimeSchedule::insert($data);
//            $showtime_schedules = \DB::table('showtime_schedules')->insert($data);
            $add_film_tickets = \DB::table('film_tickets')->insert($film_tickets);
            $update_session_showtime_code = updateBatch('sessions',$session_arr);
            if ($update_session_showtime_code&&$showtime_schedules&&$add_film_tickets){
                \DB::commit();
                logs($this->user,json_encode(['type'=>'showtime_schedule','msg'=>'添加营业日'.$business_date.'放映计划成功','info'=>$data]));
                return success('','开售成功');
            }
        }catch (\Exception $e){
            \DB::rollBack();
            logs($this->user,json_encode(['type'=>'showtime_schedule','msg'=>'添加营业日'.$business_date.'放映计划失败','info'=>$data]));
            return error('开售失败');
        }
    }

    /**
     * @param $cinema_code
     * @param $business_date
     * @param $unique 连场的array(screen_code=>playthrougth_name)
     * @param $num 连场的场次总数
     * @param $data 连场的场次详情
     * @return array
     *处理一个营业日内连场信息
     */
    private function group_sort($cinema_code,$business_date,$unique, $num, $data,$cinema_info) {
        $info = [];
        $sesson_arr = [];
        foreach ($unique as $value => $key) {
            $data_format = [];
            $data_format['name'] = $value;
            $data_format['code'] = get_showtime_schedule_code();
            $data_format['screen_code'] = $key;
            $data_format['screen_name'] = Screen::where(['code'=>$key,'cinema_code'=>$cinema_code])->value('name')?Screen::where(['code'=>$key,'cinema_code'=>$cinema_code])->value('name'):'不存在';
            $data_format['cinema_code'] = $cinema_code;
            $data_format['cinema_name'] = $cinema_info['name'];
            $data_format['cinema_status'] = $cinema_info['status'];
            $data_format['business_date'] = $business_date;
            $data_format['playthrough_flag'] = 1;
            $data_format['lowest_price'] = $data_format['default_price'] = $data_format['local_default_price'] = 0;
            $data_format['start_time'] = $data_format['end_time'] = $data[0]['start_time'];
            for ($i = 0; $i < $num; $i++) {
                if ($data[$i]['screen_code'] == $key&&$data[$i]['playthrough_name']==$value) {
                    $sessons = [];
                    $sessons['id'] = $data[$i]['id'];
                    $sessons['showtime_schedule_code'] = $data_format['code'];
                    $sesson_arr[] = $sessons;
                    $data_format['lowest_price'] = $data[$i]['lowest_price'];
                    $data_format['start_time'] = $data[$i]['start_time']<$data_format['start_time']?$data[$i]['start_time']:$data_format['start_time'];
                    $data_format['end_time'] = $data[$i]['end_time']>$data_format['end_time']?$data[$i]['end_time']:$data_format['end_time'];

                    $data_format['films'][] = $data[$i];
                    $data_format['duration'] = $data_format['end_time'] - $data_format['start_time'];
                    $data_format['lowest_price'] = $data_format['default_price'] = $data_format['local_default_price'] +=$data[$i]['playthrough_price'];
                    $data_format['price_plan'][$data[$i]['code']] = $data[$i]['playthrough_price'];
                    $data_format['film_names'][] = $data[$i]['film_name'];
                    $data_format['film_codes'][] = $data[$i]['film_code'];
                    $data_format['seat_by_number'] = $data[$i]['seat_by_number'];
                    $data_format['created_at'] = date('Y-m-d H:i:s');
                    $data_format['updated_at'] = date('Y-m-d H:i:s');
                    $data_format['project_ids'][] = $data[$i]['project_id'];
                }
            }
            $data_format['start_time'] = date('Y-m-d H:i:s',$data_format['start_time']);
            $data_format['end_time'] = date('Y-m-d H:i:s',$data_format['end_time']);
            $data_format['film_names'] = ','.implode(',',$data_format['film_names']);
            $data_format['film_codes'] = ','.implode(',',$data_format['film_codes']);
            $data_format['films'] = json_encode($data_format['films']);
            $data_format['price_plan'] = json_encode($data_format['price_plan']);
            $data_format['project_ids'] = ','.implode(',',$data_format['project_ids']);
            $info[] = $data_format;
        }
        return array('info'=>$info,'session_arr'=>$sesson_arr);
    }

    /**
     * @param $data
     * @return array
     * 生成电影票池数据
     */
    public function add_session_seat($data){
        if (count($data)==0){
            return error('发售信息为空');
        }
        $session_seat_arr = [];
        foreach ($data as $key=>$val){
            $seats = Seats::where(['screen_code'=>$val['screen_code'],'status'=>1])->get();
            foreach ($seats as $v){
                $session_seat = [];
                $session_seat['code'] = get_session_seat_code();
                $session_seat['cinema_code'] = $val['cinema_code'];
                $session_seat['cinema_name'] = $val['cinema_name'];
                $session_seat['cinema_status'] = $val['cinema_status'];
                $session_seat['screen_code'] = $val['screen_code'];
                $session_seat['screen_name'] = $val['screen_name'];
                $session_seat['showtime_schedule_code'] = $val['code'];
                $session_seat['showtime_schedule_name'] = $val['name'];
                $session_seat['start_time'] = $val['start_time'];
                $session_seat['end_time'] = $val['end_time'];
                $session_seat['playthrough_flag'] = $val['playthrough_flag'];
                $session_seat['seat_by_number'] = $val['seat_by_number'];
                $session_seat['duration'] = $val['duration'];
                $session_seat['seat_code'] = $v['code'];
                $session_seat['row_num'] = $v['row_num'];
                $session_seat['column_num'] = $v['column_num'];
                $session_seat['x_coord'] = $v['x_coord'];
                $session_seat['y_coord'] = $v['y_coord'];
                $session_seat['group_code'] = $v['group_code'];
                $session_seat['default_price'] = $val['default_price'];
                $session_seat['local_default_price'] = $val['local_default_price'];
                $session_seat['lowest_price'] = $val['lowest_price'];
                $session_seat['price_plan'] = $val['price_plan'];
                $session_seat['films'] = $val['films'];
                $session_seat['business_date'] = $val['business_date'];
                $session_seat_arr[] = $session_seat;
            }
        }
        return $session_seat_arr;
    }

    /**
     * @param Request $request
     * 放映计划删除/停售
     */
    public function delete_showtime_schedules(Request $request){

        if (!$this->user['data']->can('showtime_schedule_manager')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$showtime_schedules_code = $request->showtime_schedules_code){
            return error('放映计划编码缺失');
        }
        $showtime_schedules = ShowtimeSchedule::where(['code'=>$showtime_schedules_code,'status'=>1,'cinema_code'=>$cinema_code])->first();

        if (!$showtime_schedules){
            return error('放映计划编码不存在或已停售、已注销');
        }
        $now_time = Carbon::now();
        $start_time = Carbon::parse($showtime_schedules->start_time);
        if ($now_time->gt($start_time)){
            return error('放映开始后不可停售');
        }

        $ticket_count = FilmTicket::where('showtime_schedule_code','=',$showtime_schedules_code)->whereIn('status',[3,4])->count();
        if ($ticket_count>0){
            return error('存在已售电影票，不可做停售操作');
        }

        $showtime_schedules->status = 2;
        if ($showtime_schedules->save()){
            logs($this->user,'停售营业日：'.$showtime_schedules->business_date.'放映计划'.$showtime_schedules->name.'成功');
            return success('','已停售');
        }else{
            logs($this->user,'停售营业日：'.$showtime_schedules->business_date.'放映计划'.$showtime_schedules->name.'失败');
            return error('停售失败');
        }

    }

    /**
     * @param Request $request
     * 暂停放映计划
     */
    public function stop_showtime_schedules(Request $request){

        if (!$this->user['data']->can('showtime_schedule_manager')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$showtime_schedules_code = $request->showtime_schedules_code){
            return error('放映计划编码缺失');
        }
        $showtime_schedules = ShowtimeSchedule::where(['code'=>$showtime_schedules_code,'cinema_code'=>$cinema_code])->where('status','!=',2)->first();
        if (!$showtime_schedules){
            return error('放映计划编码不存在或已删除');
        }
//        $count = FilmTicket::where(['cinema_code'=>$cinema_code,'showtime_schedule_code'=>$showtime_schedules_code])
//            ->where('status','!=',1)
//            ->where('status','!=',5)->count();
//        if ($count>0){
//            return error('存在已锁定、已售出、已预售电影票！不可删除放映计划');
//        }
        $now_time = Carbon::now();
        $start_time = Carbon::parse($showtime_schedules->start_time);
        if ($now_time->gt($start_time)){
            return error('放映开始后不可停售');
        }
        $showtime_schedules->status = 3;
        if ($showtime_schedules->save()){
            logs($this->user,'暂停营业日：'.$showtime_schedules->business_date.'放映计划'.$showtime_schedules->name.'成功');
            return success('','已停售');
        }else{
            logs($this->user,'暂停营业日：'.$showtime_schedules->business_date.'放映计划'.$showtime_schedules->name.'失败');
            return error('停售失败');
        }

    }

    /**
     * @param Request $request
     * 放映计划复售
     */
    public function restart_showtime_schedules(Request $request){

        if (!$this->user['data']->can('showtime_schedule_manager')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$showtime_schedules_code = $request->showtime_schedules_code){
            return error('放映计划编码缺失');
        }
        $showtime_schedules = ShowtimeSchedule::where(['code'=>$showtime_schedules_code,'status'=>3,'cinema_code'=>$cinema_code])->first();
        if (!$showtime_schedules){
            return error('放映计划编码不存在或已复售、已删除');
        }
        $now_time = Carbon::now();
        $start_time = Carbon::parse($showtime_schedules->start_time);
        if ($now_time->gt($start_time)){
            return error('放映开始后不可复售');
        }
        $showtime_schedules->status = 1;
        if ($showtime_schedules->save()){
            logs($this->user,'复售营业日：'.$showtime_schedules->business_date.'放映计划'.$showtime_schedules->name.'成功');
            return success('','已复售');
        }else{
            logs($this->user,'复售营业日：'.$showtime_schedules->business_date.'放映计划'.$showtime_schedules->name.'失败');
            return error('复售失败');
        }

    }



    /**
     * @param Request $request
     * 修改排片票价方案
     */
    public function set_session_price_plan(Request $request){

        if (!$this->user['data']->can('session_film')){
            return error('NoPermission');
        }

        if (!$layout_film_ids = $request->input('layout_film_ids')){
            return error('排片id缺失');
        }

        if (!$price_plan_id = $request->input('price_plan_id')){
            return error('票价方案id缺失');
        }
        $layout_film_ids = explode(',',$layout_film_ids);
        $count = count($layout_film_ids);
        $res_count = Session::whereIn('id',$layout_film_ids)->where('playthrough_flag','=',2)->count();
        if ($count!=$res_count){
            return error('排片id中存在错误');
        }
        $showtime_schedule_count = Session::whereIn('id',$layout_film_ids)->where('showtime_schedule_code','!=','')->count();
        if ($showtime_schedule_count>0){
            return error('已发售后不可修改排片计划');
        }

        $price_plan=PricePlan::where('status','=',1)->find($price_plan_id);
        $ticket_types = PriceplanTickettypes::where(['priceplan_tickettypes.price_plan_id'=>$price_plan_id])
            ->join('ticket_types','priceplan_tickettypes.ticket_type_id','=','ticket_types.id')
            ->select('ticket_types.*')
            ->get();
        $price_plan['ticket_type'] = $ticket_types;
        if (!$price_plan){
            return error('票价方案不存在');
        }

        $ticket_type_ids = PriceplanTickettypes::where('price_plan_id','=',$price_plan_id)->pluck('ticket_type_id')->toArray();

        if (!$ticket_type_ids){
            return error('票价类型为空');
        }
        $lowest_plan_price = TicketType::whereIn('id',$ticket_type_ids)->min('ticket_price');

        $data = [];
        foreach ($layout_film_ids as $val){
            $film_info = Session::where(['sessions.id'=>$val,'films.status'=>1])
                ->select('sessions.*','films.lowest_price','screens.name as screen_name','films.name as film_name')
                ->join('screens','screens.code','=','sessions.screen_code')
                ->join('films','films.code','=','sessions.film_code')->first();
            if ($film_info->lowest_price>$lowest_plan_price){
                $data[] = '票价方案最低票价低于'.$film_info->screen_name.'时间为'.$film_info->b24h_start_time.'~'.$film_info->b24h_end_time.'的影片《'.$film_info->film_name.'》的最低票价';
            }
        }

        if (count($data)>0){
            return error('修改票价方案失败',$data);
        }else{
            $res = Session::whereIn('id',$layout_film_ids)->update(['price_plan'=>$price_plan]);
            if ($res){
                logs($this->user,'修改票价方案id为：'.implode(',',$layout_film_ids).'成功');
                return success('','编辑成功');
            }else{
                return error('编辑失败');
            }
        }


    }

    /**
     * @param Request $request
     * 修改计划管理中是否对号入座
     */
    public function set_seat_by_number(Request $request){

        if (!$this->user['data']->can('session_film')){
            return error('NoPermission');
        }

        if (!$id = $request->input('id')){
            return error('场次id缺失');
        }
        if (!$seat_by_number = $request->input('seat_by_number')){
            return error('场次对号入座状态缺失');
        }
        $layout_film_info = Session::where('status','=',1)->find($id);
        if (!$layout_film_info){
            return error('排片不存在');
        }
        if($layout_film_info->showtime_schedule_code){
            return error('已发售排片对号入座信息不可修改');
        }
        if ($layout_film_info->playthrough_flag==1){
            return error('连场排片不可修改');
        }
        $layout_film_info->seat_by_number = $seat_by_number;
        $status = $seat_by_number==1?'是':'否';
        if ($layout_film_info->save()){
            logs($this->user,'修改营业日'.$layout_film_info->business_date.'的排片：'.$layout_film_info->code.'是否对号入座状态为：'.$status);
            return success($layout_film_info->id,'修改成功');
        }else{
            logs($this->user,'修改营业日'.$layout_film_info->business_date.'的排片：'.$layout_film_info->code.'是否对号入座状态失败');
            return error('修改失败!');
        }

    }


    /**
     * @param Request $request
     * 查询电影票池
     */
    public function get_film_tickets(Request $request){
        if (!$this->user['data']->can('buy_ticket')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        if (!$showtime_schedule_code = $request->input('showtime_schedule_code')){
            return error('放映计划编码缺失');
        }
        $count = ShowtimeSchedule::where(['cinema_code'=>$cinema_code,'code'=>$showtime_schedule_code])->count();
        if ($count==0){
            return error('放映计划不存在');
        }
        $status = $request->input('status');
        $session_seat = \DB::table('film_tickets');
        $status&&$session_seat->where('status','=',$status);
        $session_seat->where('showtime_schedule_code','=',$showtime_schedule_code);
        $data = $session_seat->select('code','seat_code','row_num','column_num','x_coord','y_coord','group_code','status')->get();
        return success($data,'查询成功');
    }

    /**
     * @param Request $request
     * 场次排片表
     */
    public function get_session_list(Request $request){

        if (!$this->user['data']->can('statistic_report')){
            return error('NoPermission');
        }

        $cinema_code = $this->user['data']['cinema_code'];
        $user_type = $this->user['data']['type'];

        $cinema_name = $request->cinema_name;
        $screen_name = $request->screen_name;
        $film_name = $request->film_name;
        $start_time = $request->start_time;
        $end_time = $request->end_time;

        $session_list = \DB::table('sessions')
            ->where('showtime_schedule_code','!=','')
            ->join('cinemas','cinemas.code','sessions.cinema_code')
            ->join('screens','screens.code','sessions.screen_code')
            ->join('films','films.code','sessions.film_code');

        $user_type==1&&$cinema_name&&$session_list->where('cinemas.name','like','%'.$cinema_name.'%');
        $user_type==2&&$session_list->where('sessions.cinema_code','=',$cinema_code);
        $film_name&&$session_list->where('films.name','like','%'.$film_name.'%');
        $screen_name&&$session_list->where('screens.name','like','%'.$screen_name.'%');
        $start_time&&$end_time&&$session_list->whereBetween('sessions.business_date',[$start_time,$end_time]);
        $session_list->select('sessions.*','cinemas.name as cinema_name','screens.name as screen_name','films.name as film_name','films.lowest_price as lowest_price');
        $session_list->orderBy('start_time','desc');
        $data = $session_list->paginate(15);

        return success($data,'查询成功');
    }


}
